package com.ohs.controller.before;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.ohs.service.ITradeService;
import com.ohs.utils.AlipayConfigQRCode;
import com.ohs.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/trade")
public class TradeController {

    @Autowired
    private ITradeService iTradeService;

    //跳转到购物车页面
    @GetMapping("/toShopCarPage")
    public String toShopCarPage(Model model, HttpSession session){
        return this.iTradeService.findAllShopCar(model, session);
    }

    //根据carId删除购物车记录
    @PostMapping("/deleteShopCarByCarId")
    @ResponseBody
    public ResponseResult deleteShopCarByCarId(Integer carId){
        return this.iTradeService.deleteShopCarByCarId(carId);
    }

    //批量删除
    @PostMapping("/deleteBatchShopCar")
    @ResponseBody
    public ResponseResult deleteBatchShopCar(@RequestBody List<Integer> carId){
        return this.iTradeService.deleteBatchShopCar(carId);
    }

    //减购物车记录的数量
    @PostMapping("/modifyQuantity")
    @ResponseBody
    public ResponseResult modifyQuantity(Integer carId, Integer quantity, Integer productId){
        return this.iTradeService.modifyQuantity(carId, quantity, productId);
    }

    //去到生成订单页面
    @RequestMapping("/toGenerateOrderPage")
    public String toGenerateOrderPage(HttpServletRequest request,Model model, HttpSession session){
        String totalMoney = request.getParameter("totalMoney");
        //System.out.println(totalMoney);
        String carId = request.getParameter("carId");
        //System.out.println(carId);
        String[] strId = carId.split(",");
        List<Integer> ids = new ArrayList<>();
        for (String i: strId){
            Integer id = Integer.parseInt(i);
            ids.add(id);
        }
        model.addAttribute("totalMoney", totalMoney);
        return this.iTradeService.toGenerateOrderPage(ids, model, session);
    }

    //支付后修改订单status为已收货
    @PostMapping("/udateOrderStatus")
    @ResponseBody
    ResponseResult udateOrderStatus(Integer userId, Integer proId){
        return this.iTradeService.updateOrderStatusByUserIdAndProId(userId, proId);
    }

    @RequestMapping("/toPay")
    @ResponseBody
    public String toPay(String proName, String orderId, String totalNum, String totalMoney) throws AlipayApiException {
        //获得初始化的AlipayClient
        //System.out.println(orderId+":"+proName+":"+totalNum+":"+totalMoney);
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigQRCode.gatewayUrl,
                AlipayConfigQRCode.app_id,
                AlipayConfigQRCode.merchant_private_key, "json",
                AlipayConfigQRCode.charset,
                AlipayConfigQRCode.alipay_public_key,
                AlipayConfigQRCode.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //这里设置支付后跳转的地址
        alipayRequest.setReturnUrl(AlipayConfigQRCode.return_url);

        //付款金额，必填
//        String total_amount = String.valueOf(bill.getTicketnum()*bill.getPrice());
        String total_amount = totalMoney;
        //订单名称，必填
//        String subject ="用户"+user.getAccount()+"影票订单";
        String subject = proName;

        String out_trade_no = orderId;
        //商品描述，可空
//        String body = "用户订购商品个数：" + bill.getTicketnum();
        String body = null;

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "5m";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;

    }

    //去到订单评价页面===================================================================================================
    @GetMapping("/toOrderCommentPage")
    public String toOrderCommentPage(HttpSession session, Model model){
        return this.iTradeService.findReceivedGoods(session, model);
    }

    @PostMapping("/commentByUserIdAndProId")
    @ResponseBody
    public ResponseResult commentByUserIdAndProId(Integer userId, Integer proId, String comment){
        return this.iTradeService.commentByUserIdAndProId(userId, proId, comment);
    }

    @RequestMapping("/toOrderCommentedPage")
    public String toOrderCommentedPage(HttpSession session, Model model){
        return this.iTradeService.findCommentByUserId(session, model);
    }

    //查看评论
    @PostMapping("/findComments")
    @ResponseBody
    public ResponseResult findComments(Integer commentId){
        return this.iTradeService.findCommentsByCommentId(commentId);
    }

    //修改评论
    @PostMapping("/updateComments")
    @ResponseBody
    public ResponseResult updateComments(Integer commentId, String comment){
        return this.iTradeService.updataComments(commentId, comment);
    }

}
